﻿using System.Windows;
using DSPL.Services;
using DSPL.Contracts;
using DSPL.Common;
using System.Data;
using DSPL.Services.Services;
using DSPL.Contracts.Common;
using DSPL.Contracts.ViewModel;
using DSPL.Contracts.Command;
using DSPL.Finac.Common;
using System;
using System.Windows.Input;
using DSPL.Common.Classes;
using System.Collections.Generic;
using DSPL.Contracts.Interfaces;
using DSPL.Services.Rules;

namespace DSPL.Finac.ViewModel
{
    public class PurchaseOrderViewModelOld : BaseViewModel
    {
        private bool isRefNoFocused;
        private bool isCurrencyCodeFocused;
        private bool isSupplierCodeFocused;
        private bool isCostCentreFocused;
        private bool isTxnDateFocused;
        private bool isDeliveryDateFocused;
        private bool isTaxComCodeFocused;
        private bool isExchangeRateEnabled;
        private bool isExchangeRateFocused;
        private bool isCurrencyCodeEnabled;
        private bool isPoTypeEnabled;
        private int itemRowIndex;
        private ICommand refreshCurrencyData;
        private ICommand calculation;
        private ICommand itemCodeLostFocus;
        private ICommand currencyCodeLostFocus;
        private double totalTax;
        private double totalDiscount;
        private double totalAmount;
        private DataTable _dtPoTaxData;
        private int _txn002ConCode;
        private Visibility  isApproveButtonVisible;
        private HelpNames _refNoHelpName;


        #region Define properties

        public bool IsCurrencyCodeFocused
        {
            get { return isCurrencyCodeFocused; }
            set
            {
                isCurrencyCodeFocused = value;
                this.OnPropertyChanged("IsCurrencyCodeFocused");
            }
        }

        public bool IsSupplierCodeFocused
        {
            get { return isSupplierCodeFocused; }
            set
            {
                isSupplierCodeFocused = value;
                this.OnPropertyChanged("IsSupplierCodeFocused");

            }
        }

        public bool IsCostCentreFocused
        {
            get { return isCostCentreFocused; }
            set
            {
                isCostCentreFocused = value;
                this.OnPropertyChanged("IsCostCentreFocused");

            }
        }

        public bool IsRefNoFocused
        {
            get { return isRefNoFocused; }
            set
            {
                isRefNoFocused = value;
                this.OnPropertyChanged("IsRefNoFocused");

            }
        }

        public bool IsTxnDateFocused
        {
            get { return isTxnDateFocused; }
            set
            {
                isTxnDateFocused = value;
                this.OnPropertyChanged("IsTxnDateFocused");

            }
        }

        public bool IsDeliveryDateFocused
        {
            get { return isDeliveryDateFocused; }
            set
            {
                isDeliveryDateFocused = value;
                this.OnPropertyChanged("IsDeliveryDateFocused");

            }
        }

        public bool IsExchangeRateFocused
        {
            get { return isExchangeRateFocused; }
            set
            {
                isExchangeRateFocused = value;
                this.OnPropertyChanged("IsExchangeRateFocused");

            }
        }

        public bool IsTaxComCodeFocused
        {
            get { return isTaxComCodeFocused; }
            set
            {
                isTaxComCodeFocused = value;
                this.OnPropertyChanged("IsTaxComCodeFocused");

            }
        }
       
        public double TotalTax
        {
            get
            {
                return totalTax;
            }
            set
            {
                totalTax = value;
                this.OnPropertyChanged("TotalTax");
            }
        }

        public double TotalDiscount
        {
            get
            {
                return totalDiscount;
            }
            set
            {
                totalDiscount = value;
                this.OnPropertyChanged("TotalDiscount");
            }
        }

        public double TotalAmount
        {
            get
            {
                return totalAmount;
            }
            set
            {
                totalAmount = value;
                this.OnPropertyChanged("TotalAmount");
            }
        }

        public int ItemRowIndex
        {
            get
            {
                return itemRowIndex;
            }
            set
            {
                itemRowIndex = value;
                OnPropertyChanged("ItemRowIndex");
            }
        }


        public bool IsExchangeRateEnabled
        {
            get
            {
                return isExchangeRateEnabled;
            }

            set
            {
                isExchangeRateEnabled = value;
                this.OnPropertyChanged("IsExchangeRateEnabled");
            }
        }

        public bool IsCurrencyCodeEnabled
        {
            get
            {
                return isCurrencyCodeEnabled;
            }

            set
            {
                isCurrencyCodeEnabled = value;
                this.OnPropertyChanged("IsCurrencyCodeEnabled");
            }
        }

        public bool IsPoTypeEnabled
        {
            get
            {
                return isPoTypeEnabled;
            }

            set
            {
                isPoTypeEnabled = value;
                this.OnPropertyChanged("IsPoTypeEnabled");
            }
        }

        public Visibility IsApproveButtonVisible
        {
            get
            {
                return isApproveButtonVisible;
            }

            set
            {
                isApproveButtonVisible = value;
                this.OnPropertyChanged("IsApproveEnabled");
            }
        }

        public HelpNames RefNoHelpName
        {
            get
            {
                return _refNoHelpName;
            }

            set
            {
                _refNoHelpName = value;
                this.OnPropertyChanged("RefNoHelpName");
            }
        }



        #endregion

        # region Commands

        public ICommand RefreshCurrencyData
        {
            get
            {
                if (this.refreshCurrencyData == null)
                {
                    this.refreshCurrencyData = new RelayCommand(RefreshCurrencyDataExecuted);
                }
                return this.refreshCurrencyData;
            }
        }

        public ICommand Calculation
        {
            get
            {
                if (this.calculation == null)
                {
                    this.calculation = new RelayCommand(CalculateAmountsExecuted);
                }
                return this.calculation;
            }
        }

        public ICommand ItemCodeLostFocus
        {
            get
            {
                if (this.itemCodeLostFocus == null)
                {
                    this.itemCodeLostFocus = new RelayCommand(ItemCodeLostFocusExecuted);
                }
                return this.itemCodeLostFocus;
            }
        }


        public ICommand CurrencyCodeLostFocus
        {
            get
            {
                if (this.currencyCodeLostFocus == null)
                {
                    this.currencyCodeLostFocus = new RelayCommand(CurrencyCodeLostFocusExecuted);
                }
                return this.currencyCodeLostFocus;
            }
        }
        #endregion

        #region Constructor

        public PurchaseOrderViewModelOld()
            : base()
        {
            MessageTitle = "Purchase Order ";
        }

        #endregion

        /// <summary>
        /// Validate mandatory data before save
        /// </summary>
        /// <param name="obj"></param>
        protected override void PreDataValidateExecuted(object obj)
        {
            IsRefNoFocused = false;
            IsCurrencyCodeFocused = false;
            IsSupplierCodeFocused = false;
            IsCostCentreFocused = false;
            IsTxnDateFocused = false;
            IsExchangeRateFocused = false;
            IsTaxComCodeFocused = false;

            var messageService = new MessageService();
            var masterReadService = new MasterReadService();
            if ((FormMode == Modes.Edit) && (String.IsNullOrEmpty(CurrentRow["RefNo"].ToString().Trim())))
            {
                messageService.ShowMessage(MessageText.ReferenceNoNotEmpty, MessageTitle, MessageType.InfoOK);
                IsRefNoFocused = true;
                this.IsValid = false;
                return;
            }

            if (CurrentRow["TxnDate"] == DBNull.Value)
            {
                messageService.ShowMessage(MessageText.TransactionDateNotEmpty, MessageTitle, MessageType.InfoOK);
                IsTxnDateFocused = true;
                this.IsValid = false;
                return;
            }
            else
            {
                var stockRules = new StockRulesService();
                if (!stockRules.ValidateStockTransactionDate(Convert.ToDateTime(CurrentRow["TxnDate"]), CurrentRow["RefNo"].ToString().Trim(), BlockBackDatedTransaction, ReportGroup))
                {
                    IsTxnDateFocused = true;
                    this.IsValid = false;
                    return;
                }

                if (CurrentRow["DeliveryDate"] == DBNull.Value)
                {
                    MessageBox.Show("Delivery Date cannot be blank.", MessageTitle, MessageBoxButton.OK, MessageBoxImage.Information);
                    IsDeliveryDateFocused = true;
                    this.IsValid = false;
                    return;
                }


                if (Convert.ToDateTime(CurrentRow["DeliveryDate"]) < Convert.ToDateTime(CurrentRow["TxnDate"]))
                {
                    messageService.ShowMessage(MessageText.InvalidDeliveryDate, MessageTitle, MessageType.InfoOK);
                    CurrentRow["DeliveryDate"] = CurrentRow["TxnDate"];
                    IsDeliveryDateFocused = true; ;
                    this.IsValid = false;
                    return;
                }
            }

            if (CurrentRow["SupplierPk"] == DBNull.Value || Convert.ToInt32(CurrentRow["SupplierPk"]) == 0)
            {
                messageService.ShowMessage(MessageText.SupplierNotEmpty, MessageTitle, MessageType.InfoOK);
                IsSupplierCodeFocused = true;
                this.IsValid = false;
                return;
            }
            else
            {
                if (!masterReadService.IsSupplierActive(Convert.ToInt32(CurrentRow["SupplierPk"])))
                {
                    messageService.ShowMessage(MessageText.SupplierNotActive, MessageTitle, MessageType.InfoOK);
                    IsSupplierCodeFocused = true;
                    this.IsValid = false;
                    return;
                }
            }

            if (CurrentRow["CurPk"] == DBNull.Value || Convert.ToInt32(CurrentRow["CurPk"]) == 0)
            {
                messageService.ShowMessage(MessageText.CurrencyCodeNotEmpty, MessageTitle, MessageType.InfoOK);
                IsCurrencyCodeFocused = true;
                this.IsValid = false;
                return;
            }


            if (CurrentRow["CostPk"] == DBNull.Value || Convert.ToInt32(CurrentRow["CostPk"]) == 0)
            {
                messageService.ShowMessage(MessageText.CostCodeNotEmpty, MessageTitle, MessageType.InfoOK);
                IsCostCentreFocused = true;
                this.IsValid = false;
                return;
            }

            if (CurrentRow["CurRate"] == DBNull.Value || Convert.ToDouble(CurrentRow["CurRate"]) <= 0)
            {
                messageService.ShowMessage(MessageText.CurrencyRateNotZero, MessageTitle, MessageType.InfoOK);
                IsExchangeRateFocused = true;
                this.IsValid = false;
                return;
            }


            if (CurrentRow["TaxComPk"] != DBNull.Value && Convert.ToInt32(CurrentRow["TaxComPk"]) != 0)
            {
                if (!masterReadService.IsTaxCombinationActive(Convert.ToInt32(CurrentRow["TaxComPk"])))
                {
                    messageService.ShowMessage(MessageText.TaxCombinationNotActive, MessageTitle, MessageType.InfoOK);
                    IsTaxComCodeFocused = true;
                    this.IsValid = false;
                    return;
                }
            }

            if (!CheckItemStatus())
            {
                this.IsValid = false;
                return;

            }

            if (!CheckTaxCombinationStatus())
            {
                this.IsValid = false;
                return;
            }

            if (DtChildTransaction.Select("ItemCode<>'' AND (PurPrice> 0.00 AND qty >0.00)").Length == 0)
            {
                messageService.ShowMessage(MessageText.NoValidData, MessageTitle, MessageType.InfoOK);
                this.IsValid = false;
                return;
            }

            // To delete empty rows from the child table            

            for (int i = DtChildTransaction.Rows.Count - 1; i >= 0; i--)
            {
                if (string.IsNullOrEmpty(DtChildTransaction.Rows[i]["ItemCode"].ToString()) || (DtChildTransaction.Rows[i]["Qty"]) == DBNull.Value || (DtChildTransaction.Rows[i]["PurPrice"]) == DBNull.Value)
                    DtChildTransaction.Rows[i].Delete();
            }
            DtChildTransaction.AcceptChanges();

            double currencyRate = Convert.ToDouble(CurrentRow["CurRate"]);
            foreach (DataRow drDataDetail in DtChildTransaction.Rows)
            {
                drDataDetail["TxnDate"] = CurrentRow["TxnDate"];
                drDataDetail["BalQty"] = drDataDetail["Qty"];
                drDataDetail["TxnType"] = "10";
                drDataDetail["CostPrice"] = (drDataDetail["PurPrice"] != DBNull.Value ? Math.Round(Convert.ToDouble(drDataDetail["PurPrice"]) * currencyRate, 2) : 0.00);
                drDataDetail["BDisAmt"] = (drDataDetail["DisAmt"] != DBNull.Value ? Math.Round(Convert.ToDouble(drDataDetail["DisAmt"]) * currencyRate, 2) : 0.00);
                drDataDetail["BAmt"] = (drDataDetail["Amt"] != DBNull.Value ? Math.Round(Convert.ToDouble(drDataDetail["Amt"]) * currencyRate, 2) : 0.00);

            }

            CurrentRow["TxnType"] = "10";
            CurrentRow["BTotalDis"] = Math.Round(totalDiscount * currencyRate, 2);
            CurrentRow["BTotalTax"] = Math.Round(totalTax * currencyRate, 2);
            CurrentRow["BTotalAmt"] = Math.Round(totalAmount * currencyRate, 2);
            CurrentRow["prtCopy"] = 0;


            int poType = Convert.ToInt32(CurrentRow["PoType"]);

            if (FormMode == Modes.New)
            {
                RefGenCode = "SPOT";
            }
            else
            {
                switch (poType)
                {
                    case 1:
                        RefGenCode = "SPOL";
                        break;
                    case 2:
                        RefGenCode = "SPOS";
                        break;
                    case 3:
                        RefGenCode = "SPOA";
                        break;
                }
            }

            CalculateAmounts();

            this.IsValid = true;
        }

        protected override void PostResetDefaultExecuted(object obj)
        {

        }
               

        protected override void RefreshExternalDataObjectsExecueted(object obj)
        {
            base.RefreshExternalDataObjectsExecueted(obj);
            //AddColumnsToChildTable();

            if (FormMode == Modes.New)
            {
                var masterReadService = new MasterReadService();
                CurrentRow["TxnDate"] = DateTime.Now;
                CurrentRow["DeliveryDate"] = DateTime.Now;

                CurrentRow["PoType"] = 1;
                CurrentRow["CurPk"] = masterReadService.GetCurrencyKey(GlobalVariables.BaseCurrency);
                CurrentRow["CurRate"] = 1.00;
                var commonReadService = new CommonReadService();
                CurrentRow["CostPk"] = commonReadService.GetUserWiseCostCenter();
                OnPropertyChanged("CurrentRow");
            }

            LoadTransactionSpecificData();
            SetRefernceNoHelpName();
        }

       

        protected override void AddAddionalReportParametersExecuted(object obj)
        {
            base.AddAddionalReportParametersExecuted(obj);

            if (AdditionalReportParameters == null)
            {
                AdditionalReportParameters = new List<IReportParameters>();
            }
            AdditionalReportParameters.Add(new ReportParameters() { ParameterIndex = 8, ParameterName = "VatCompanyTaxNo", InputValue = GlobalVariables.VatCompanyTaxNo });
        }

        protected override void SetDataSourcesAndProperties()
        {
            var masterReadService = new MasterReadService();
            _txn002ConCode = masterReadService.GetConCodeStatusDetails("TXN0002");

            IsApproveButtonVisible = (_txn002ConCode == 1) ? Visibility.Visible : Visibility.Collapsed;

        } 
       
        protected override void EnableDisableSpecificControls()
        {
            base.EnableDisableSpecificControls();

            if (GlobalVariables.SystemCurrency.Trim().ToUpper() == "LOCAL")
            {
                IsCurrencyCodeEnabled = false;
                IsExchangeRateEnabled = false;
            }
            else
            {
                IsCurrencyCodeEnabled = IsExchangeRateEnabled = ((FormMode == Modes.New || FormMode == Modes.Edit) ? true : false);

            }

            if (FormMode == Modes.New)
            {
                IsPoTypeEnabled = true;
            }
            else
            {
                IsPoTypeEnabled = false;
            }
        }
        
        private bool CheckItemStatus()
        {
            var masterReadService = new MasterReadService();
            var messageService = new MessageService();
            foreach (DataRow drGridData in DtChildTransaction.Rows)
            {
                string itemCode = Convert.ToString(drGridData["ItemCode"]);

                if (itemCode == string.Empty)
                {
                    continue;
                }
                else
                {
                    if (!masterReadService.IsItemActive(Convert.ToInt32(drGridData["ItemPk"])))
                    {
                        messageService.ShowMessage("Inactive item is selected. Please change to enter transactions.\nItem Code:" + itemCode, MessageType.InfoOK);
                        return false;
                    }
                }

            }
            return true;
        }

        private bool CheckTaxCombinationStatus()
        {
            var masterReadService = new MasterReadService();
            var messageService = new MessageService();
            foreach (DataRow drGridData in DtChildTransaction.Rows)
            {
                string taxComCode = Convert.ToString(drGridData["TaxComCode"]);

                if (taxComCode == string.Empty)
                {
                    continue;
                }
                else
                {
                    if (!masterReadService.IsTaxCombinationActive(Convert.ToInt32(drGridData["TaxComPk"])))
                    {
                        messageService.ShowMessage("Inactive tax combination is selected. Please change to enter transactions. Tax Combination Code:" + taxComCode, MessageType.InfoOK);
                        return false;
                    }
                }

            }
            return true;
        }

        private void CalculateAmounts()
        {
            string itemCode;
            double purchasePrice, quantity, totalValue, totalDiscount, discount, total, sumTotalDiscount, sumTotal;

            totalTax = totalAmount = 0.00;
            int noOfDecimalPlaces = GlobalVariables.CurValDecimalPoints;
            int sequenceNo = 1;
            sumTotalDiscount = sumTotal = 0.00;
            foreach (DataRow drDataRow in DtChildTransaction.Rows)
            {
                itemCode = Convert.ToString(drDataRow["ItemCode"]);
                purchasePrice = (drDataRow["PurPrice"] == DBNull.Value ? 0.00 : Convert.ToDouble(drDataRow["PurPrice"]));
                quantity = (drDataRow["Qty"] == DBNull.Value ? 0.00 : Convert.ToDouble(drDataRow["Qty"]));
                discount = (drDataRow["DisPer"] == DBNull.Value ? 0.00 : Convert.ToDouble(drDataRow["DisPer"]));

                if (itemCode == string.Empty || purchasePrice == 0.00 || quantity == 0.00)
                {
                    drDataRow["DisAmt"] = 0.00;
                    drDataRow["Amt"] = 0.00;
                    drDataRow["SeqNo"] = 0;
                    continue;
                }

                totalValue = Math.Round(quantity * purchasePrice, noOfDecimalPlaces);
                totalDiscount = Math.Round((totalValue * discount) / 100, noOfDecimalPlaces);
                total = totalValue - totalDiscount;

                drDataRow["DisAmt"] = totalDiscount;
                drDataRow["Amt"] = total;
                drDataRow["SeqNo"] = sequenceNo;
                sequenceNo += 1;
                sumTotalDiscount += totalDiscount;
                sumTotal += total;
            }

            CommonRules commonRulesObj = new CommonRules();
            totalTax = totalAmount = 0.00;
            DataView viewChildTran = new DataView(DtChildTransaction);

            DataTable dtCopyChildTransaction = viewChildTran.ToTable("dtCopyChildTransaction", false, "PoPk", "ItemPk", "Amt", "TaxComPk",  "PurPrice", "Qty", "BAmt","TaxAmt","BTaxAmt");

            for (int i = dtCopyChildTransaction.Rows.Count - 1; i >= 0; i--)
            {
                if ((dtCopyChildTransaction.Rows[i]["ItemPk"] == DBNull.Value) || (dtCopyChildTransaction.Rows[i]["Qty"]) == DBNull.Value || (dtCopyChildTransaction.Rows[i]["PurPrice"]) == DBNull.Value)
                    dtCopyChildTransaction.Rows[i].Delete();
            }
            dtCopyChildTransaction.AcceptChanges();

            // just add this dummy field to avoid the error in the MLine_Tax_Cal stored procedure
            DataView viewGrnTax = new DataView(_dtPoTaxData);
            dtCopyChildTransaction.Columns.Add("RefNo1",typeof(Int32));
            DataTable dtCopyPoTax = viewGrnTax.ToTable("dtCopyPoTax", false, "RefPk", "ItemPk","TaxComPk", "TaxPk",  "TaxPer", "TaxRate", "Taxseq", "TaxDetAmt", "BTaxDetAmt");
             
            int poPk = CurrentRow["PoPk"]==DBNull.Value ? 0 :  Convert.ToInt32(CurrentRow["PoPk"]);
            if (FormMode == Modes.New || FormMode == Modes.Edit || FormMode == Modes.Approve)
            {
                bool isSuccess = commonRulesObj.MultipleLineTaxCalculation(dtTranDet: ref dtCopyChildTransaction, dtTaxDetailTable: ref dtCopyPoTax, curRate: Convert.ToDouble(CurrentRow["CurRate"]), whereCondition: "ItemPk<>0 AND PurPrice <> 0.00 AND qty <>0.00", keyFields: "ItemPk",  refNoValue:poPk, totalTax: out totalTax, totAmount: out totalAmount);
            }
            else
            {
                bool isSuccess = commonRulesObj.MultipleLineTaxCalculation(dtTranDet: ref  dtCopyChildTransaction, dtTaxDetailTable: ref dtCopyPoTax, curRate: Convert.ToDouble(CurrentRow["CurRate"]), whereCondition: "ItemPk<>0 AND PurPrice <> 0.00 AND qty <>0.00", keyFields: "ItemPk", refNoValue:poPk, totalTax: out totalTax, totAmount: out totalAmount, referenceNo: Convert.ToInt32(CurrentRow["PoPk"]), taxDetailTranTable: "fPoTaxDt");
            }

            CurrentRow["TotalTax"] = totalTax;
            CurrentRow["TotalAmt"] = totalAmount;
            CurrentRow["TotalDis"] = sumTotalDiscount;

            this.OnPropertyChanged("CurrentRow");
        }


        private void LoadTransactionSpecificData()
        {
            var readTransactionDta = new TransactionReadService();
           
            if (CurrentRow["PoPk"] == DBNull.Value)
            {
                _dtPoTaxData = readTransactionDta.GetPurchaseOrderTaxData((FormMode == Modes.New ? 0 : (CurrentRow["PoPk"] == DBNull.Value ? 0 : Convert.ToInt32(CurrentRow["PoPk"]))));
            }
        }

        protected override void PostDataInsertExecuted(object obj)
        {
            var transactionWriteService = new TransactionWriteService();
           
            var sqlTran = this.SqlTran;
            if (!transactionWriteService.UpdatePurchaseOrderSpecificData(CurrentRow, _dtPoTaxData, ref sqlTran))
            {
                this.IsValid = false;
            }
            else
            {
                this.IsValid = true;
                this.SqlTran = sqlTran;
            }
        }

        protected override void PostDataUpdateExecuted(object obj)
        {
            var transactionWriteService = new TransactionWriteService();
            var sqlTran = this.SqlTran;
            if (!transactionWriteService.UpdatePurchaseOrderSpecificData(CurrentRow, _dtPoTaxData, ref sqlTran))
            {
                this.IsValid = false;
            }
            else
            {
                this.IsValid = true;
                this.SqlTran = sqlTran;
            }
        }

        protected override void PreDataDeleteExecuted(object obj)
        {
            var transactionWriteService = new TransactionWriteService();
            var sqlTran = this.SqlTran;
            if (!transactionWriteService.DeletePurchaseOrderSpecificData(Convert.ToInt32(CurrentRow["PoPk"]), ref sqlTran))
            {
                this.IsValid = false;
            }
            else
            {
                this.IsValid = true;
                this.SqlTran = sqlTran;
            }

        }

        protected override void PreDataDelValidationExecuted(object obj)
        {
            if (!ValidateTransactions())
            {
                this.IsValid = false ;
            }
        }
        private void ItemCodeLostFocusExecuted(object obj)
        {
            if (FormMode == Modes.View || FormMode == Modes.Cancel || FormMode == Modes.Print)
            {
                return;
            }
            DtChildTransaction.AcceptChanges();
            TxtItem itemTextBox = (TxtItem)obj;
            string itemCode = itemTextBox.ItemCode.Trim();
            var masterReadService = new MasterReadService();
            var messageService = new MessageService();
            if (itemCode != string.Empty)
            {
                if (DtChildTransaction.Select("ItemCode='" + itemCode + "'").Length > 1)
                {
                    messageService.ShowMessage(MessageText.ItemCodeDuplicated, MessageTitle, MessageType.InfoOK);

                    DtChildTransaction.Rows[ItemRowIndex]["ItemPk"] = 0;
                    DtChildTransaction.Rows[ItemRowIndex]["ItemCode"] = string.Empty;
                    DtChildTransaction.Rows[ItemRowIndex]["ItemName"] = string.Empty;
                    DtChildTransaction.Rows[ItemRowIndex]["Qty"] = 0.00;
                    DtChildTransaction.Rows[ItemRowIndex]["Amt"] = 0.00;
                    DtChildTransaction.Rows[ItemRowIndex]["PurPrice"] = 0.00;
                    DtChildTransaction.Rows[ItemRowIndex]["CostPrice"] = 0.00;
                    DtChildTransaction.Rows[ItemRowIndex]["DisPer"] = 0.00;
                    DtChildTransaction.Rows[ItemRowIndex]["TaxComCode"] = string.Empty;
                    this.OnPropertyChanged("DtChildTransaction");
                    return;
                }

                // check the itemStatus
                if (itemTextBox.ItemCode != string.Empty)
                {
                    if (Convert.ToInt16(itemTextBox.ItemStatus) == 0)
                    {
                        messageService.ShowMessage(MessageText.InactiveItemFound, MessageTitle, MessageType.InfoOK);
                        DtChildTransaction.Rows[ItemRowIndex]["ItemPk"] = 0;
                        DtChildTransaction.Rows[ItemRowIndex]["ItemCode"] = string.Empty;
                        DtChildTransaction.Rows[ItemRowIndex]["ItemName"] = string.Empty;
                        DtChildTransaction.Rows[ItemRowIndex]["Qty"] = 0.00;
                        DtChildTransaction.Rows[ItemRowIndex]["Amt"] = 0.00;
                        DtChildTransaction.Rows[ItemRowIndex]["PurPrice"] = 0.00;
                        DtChildTransaction.Rows[ItemRowIndex]["CostPrice"] = 0.00;
                        DtChildTransaction.Rows[ItemRowIndex]["DisPer"] = 0.00;
                        DtChildTransaction.Rows[ItemRowIndex]["TaxComPk"] = string.Empty;
                        DtChildTransaction.Rows[ItemRowIndex]["TaxComCode"] = string.Empty;
                        this.OnPropertyChanged("DtChildTransaction");
                        return;
                    }
                    else
                    {
                        if (Convert.ToString(DtChildTransaction.Rows[ItemRowIndex]["TaxComCode"]).Trim() == string.Empty)
                        {
                            DtChildTransaction.Rows[ItemRowIndex]["TaxComPk"] = (CurrentRow["TaxComPk"]==DBNull.Value? 0: Convert.ToInt32(CurrentRow["TaxComPk"]));
                            DtChildTransaction.Rows[ItemRowIndex]["TaxComCode"]= (CurrentRow["TaxComPk"]==DBNull.Value ? "": masterReadService.GetTaxCombinationCode(Convert.ToInt32(CurrentRow["TaxComPk"])));
                               
                        }
                    }
                }

                this.OnPropertyChanged("DtChildTransaction");
            }
            
        }

        private void CalculateAmountsExecuted(object obj)
        {
            CalculateAmounts();
        }

        private void CurrencyCodeLostFocusExecuted(object obj)
        {
            CalculateAmounts();
        }

        private void RefreshCurrencyDataExecuted(object obj)
        {
            TxtCurrency txtCurrency = (TxtCurrency)obj;
            CurrentRow["CurRate"] = txtCurrency.CurrencyRate;
            this.OnPropertyChanged("CurrentRow");
            CalculateAmounts();
        }

        private bool ValidateTransactions()
        {
            var readTransactions = new TransactionReadService();
            if (readTransactions.ValidatePurchaseOrder(FormMode, Convert.ToInt32(CurrentRow["PoPk"])))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void SetRefernceNoHelpName()
        {
            switch (FormMode)
            {
                case Modes.Edit:
                case  Modes.Delete:
                    RefNoHelpName = HelpNames.EditPurchaseOrderHelp;
                    break;
                case Modes.Approve:
                    RefNoHelpName = HelpNames.AllocatePurchaseOrderHelp;
                    break;
                case Modes.View:
                    RefNoHelpName = HelpNames.AllPurchaseOrderHelp;
                    break;
                default:
                    RefNoHelpName = HelpNames.AllPurchaseOrderHelp;
                    break;

            }
           

        }

    }
}





